package com.taotao.service.impl;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.taotao.service.PictureService;
import com.taotao.utils.FtpUtil;
import com.taotao.utils.IDUtils;

@Service
public class PictureServiceImpl implements PictureService {
	@Value("${FTP_ADDRESS}")
	private String FTP_ADDRESS;
	@Value("${FTP_PORT}")
	private Integer FTP_PORT;
	@Value("${FTP_USERNAME}")
	private String FTP_USERNAME;
	@Value("${FTP_PASSWORD}")
	private String FTP_PASSWORD;
	@Value("${FTP_BASE_PATH}")
	private String FTP_BASE_PATH;
	@Value("${IMAGES_BASE_PATH}")
	private String IMAGES_BASE_PATH;
	

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public Map pictureUpload(MultipartFile file) {
		Map map=new HashMap();
		try {
			// 获取上传文件的原始名字
			String oldNmae = file.getOriginalFilename();
			// 生成新的文件名字
			String newName = IDUtils.genImageName() + oldNmae.substring(oldNmae.lastIndexOf("."));
			String imgPath=new DateTime().toString("yyyy/MM/dd");
			boolean falg=FtpUtil.uploadFile(FTP_ADDRESS, FTP_PORT, FTP_USERNAME, FTP_PASSWORD, FTP_BASE_PATH, imgPath, newName, file.getInputStream());
			if(falg){
				map.put("error", 0);
				map.put("url", IMAGES_BASE_PATH+"/"+imgPath+"/"+newName);
				return map;
			}
			map.put("error", 1);
			map.put("messgae","上传图片出错了");
			return map;
		} catch (IOException e) {
			map.put("error", 1);
			map.put("messgae","上传图片出现异常");
			return map;
		}
	}

}
